<?php
namespace App\Repository;
use App\Events\SendBaobeiEvent;
use App\Events\SendBaoxiaoEvent;
use App\model\Coustomer;
use App\model\Project;
use App\model\SendNoticeUser;
use App\model\UserFormId;
use App\User;
use Carbon\Carbon;
use Spatie\Permission\Models\Role;

/**
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 */
class WechatRepository
{
     protected $miniProgram;
     public function __construct()
     {
        $this->miniProgram=\EasyWeChat::miniProgram();
     }
     //得到行业消息
     public function getIndustry(){
         $this->miniProgram->template_message->getIndustry();
     }
     public function decryptData($session,$iv,$encryptData){
        return      $this->miniProgram->encryptor->decryptData($session, $iv, $encryptData);
     }
    public function sendMessage(User $user){

        $FormId=  UserFormId::where('user_id',$user->id)
            ->whereDate('created_at','>',Carbon::today()->addDays(-7))
            ->first();
        if(!$FormId){
            return true;
        }
      $result=  $this->miniProgram->template_message->send([
            'touser' => $user->userinfo->openid,
            'template_id' => 'mv4KiWAHZuYUdrAx8-qggBiVg_x2-qc3cnXlDsDHJs0',
            'page' => '/pages/index/index',
            'form_id' => $FormId->form_id,
            'data' => [
                'keyword1' => $user->name,
                'keyword2' => $user->mobile,
                'keyword3' => Carbon::now(),
                'keyword4' => '提交表单',
                // ...
            ],
        ]);
        $FormId->delete();
        return $result;
    }
    //销售线索
    public function sendXiaoshouMessage(User $user,Coustomer $coustomer,$is_mobile=1){
        $FormId=  UserFormId::where('user_id',$user->id)
            ->whereDate('created_at','>',Carbon::today()->addDays(-7))
            ->first();
        if(!$FormId){
                \Log::info('没有fromId了',$user->toArray());
            return true;
        }
        $result=  $this->miniProgram->template_message->send([
            'touser' => $user->userinfo->openid,
            'template_id' => 'Fg5X7-KoiC8m6ghkF4mZ4-Bp-hmqKnnJlH2YrSP3M5o',
            'page' => '/pages/index/index?type=1&project_id='.$coustomer->project_id ?? 0,
            'form_id' => $FormId->form_id,
            'data' => [
                'keyword1'=>Project::find($coustomer->project_id)->name ?? '未知' ,
                'keyword2' => $coustomer->name,
                'keyword3' => substr_replace($coustomer->mobile,'****',3,4),
            //    'keyword4' => $coustomer->city1.$coustomer->city2,
                'keyword4' => Coustomer::$statusMap[$coustomer->status] ?? '未跟进',
                'keyword5'=>$coustomer->created_at,

            ],
        ]);
        $FormId->delete();
        \Log::info('销售结果:11',$user->toArray());
        return $result;
    }
    //数据上报提醒
    public function sendTuiguangMessage(User $user,Project $project){
        $FormId=  UserFormId::where('user_id',$user->id)
            ->whereDate('created_at','>',Carbon::today()->addDays(-7))
            ->first();
        if(!$FormId){
            return true;
        }
        $result=  $this->miniProgram->template_message->send([
            'touser' => $user->userinfo->openid,
            'template_id' => 'ND3i7Gv1vIV0OwDu9HQVAI7WjD2g10GKYXESvjZSSBU',
            'page' => '/pages/index/index?type=2',
            'form_id' => $FormId->form_id,
            'data' => [
                'keyword1' => $project->name,
                'keyword2' => '请前往小程序更新'.date('m月d日',strtotime(Carbon::yesterday())).$project->name.'推广消费日报表',
                'keyword3' => $user->name,
            ],
        ]);
        $FormId->delete();
        return $result;
    }
    //数据上报提醒
    public function sendBaobiaoMessage(User $users,Project $project,$time){
        $sendNotice=SendNoticeUser::find(2);
        $sendUser=$sendNotice->role;
        $user=User::rightJoin('model_has_roles','model_has_roles.model_id','=','users.id')
            ->whereIn('model_has_roles.role_id',$sendUser)
            ->where(\DB::raw("find_in_set($project->project_id,project_id)"),'>',0)
            ->get()->unique('id')->values();

        if ($user->isEmpty()){
            return true;
        }
     foreach ($user as $v){
        \Log::info($v->id);
        //禁止通知
   /*     if (in_array($project->project_id,$v->no_project_id)){
            continue ;
        }*/
        event(new SendBaobeiEvent($v,$project,$time));
        $FormId=  UserFormId::where('user_id',$v->id)
            ->whereDate('created_at','>',Carbon::today()->addDays(-5))->first();
        if($FormId){
            $result=  $this->miniProgram->template_message->send([
                'touser' => $v->userinfo->openid,
                'template_id' => 'mnSltxYH_IZFO8h9TdWuGeJm6eMyMOif7A14m-y_IEg',
                'page' => 'pages/index/index?type=4&project_id='.$project->project_id.'&date='.date('Y-m-d',strtotime($time)),
                'form_id' => $FormId->form_id,
                'data' => [
                    'keyword1' =>$project->name.date('m月d日',strtotime($time)).'推广消费日报表',
                    'keyword2' => Carbon::now(),
                ],
            ]);
            $FormId->delete();
            return $result;
        }
       };
    }
    public function wechatSendBaobeiMessage(User $user,Project $project,$time){
        $officialAccount = \EasyWeChat::officialAccount();
        if(!isset($user->userWechat->openid))  {
            \Log::info('没有openid',$user->toArray());
            return true;
        }
        $r=  $officialAccount->template_message->send([
            'touser' => $user->userWechat->openid,
            'template_id' =>'bjalZAo-RsZoLtrtWdnQI0DxAqhweS8cB69WIJDWGWo',
            'url' => '',
            "miniprogram"=>[
                "appid"=>"wxb07d0e98119debaa",
                "pagepath"=>'pages/index/index?type=4&project_id='.$project->project_id.'&date='.date('Y-m-d',strtotime($time))
            ],
            'data' => [
                'first'=>'您好，推广消费日报表已完成',
                'keyword1' =>  [$project->name ?? '','#0066FF'],
                'keyword2' => [date('m月d日',strtotime($time)).'推广消费日报表','#0066FF'],
                'keyword3'=>Carbon::now(),
                'remark'=>['请登录小程序查看详情。','#0066FF']
            ,
        ]]
        );
        return $r;
    }
    public function wechatSendXiaofeiMessage(User $user,Project $project,$time,User $fromUser){
        $officialAccount = \EasyWeChat::officialAccount();
         if(!isset($user->userWechat->openid))  {
             \Log::info('没有openid',$user->toArray());
             return true;
         }
        $officialAccount->template_message->send([
            'touser' => $user->userWechat->openid,
            'template_id' =>'CicvOLArE9rMLYG1ZdyAftION-7rXnC3-pGln2Lp-jE',
            'url' => '',
            "miniprogram"=>[
                "appid"=>"wxb07d0e98119debaa",
                "pagepath"=>"pages/index/index?type=2",
            ],
            'data' => [
                'first'=>'您有一条新的消费数据上报提醒',
                'keyword1' =>  [$project->name ?? '','#0066FF'],
                'keyword2' => [$fromUser->name, '#0066FF'],
                'keyword3'=>['请更新'.date('m月d日',strtotime($time)).'推广消费日报表','#0066FF'],
                'remark'=>['请登录小程序查看详情。','#0066FF']
            ],
        ]);
    }
    public function wechatSendMessage(User $user,Coustomer $customer){
        $officialAccount = \EasyWeChat::officialAccount();

        if (!isset( $user->userWechat->openid)){
            \Log::error('发送公众信息失败:openid不存在',$user->toArray());
            return true;
        }
        try {
            $officialAccount->template_message->send([
                'touser' => $user->userWechat->openid ?? '',
                'template_id' => 'AGt9E-SgM2Yh-Y857aMFSSoKkpgyCGIVCT0d879yGcE',
                'url' => '',
                "miniprogram" => [
                    "appid" => "wxb07d0e98119debaa",
                    "pagepath" => "pages/index/index?type=3&id=".$customer->customer_id

                ],
                'data' => [
                    'first' => '您好,收到报备新通知',
                    'keyword1' =>[ $customer->project->name ?? '','#0066FF'],
                    'keyword2' => [$customer->name,'#0066FF'],
                    'keyword3' => [substr_replace($customer->mobile, '****', 3, 4),'#0066FF'],
                    'remark' => '请登录小程序查看详情。'
                ],
            ]);
        }catch (\Exception $exception){
            \Log::error('发送公众信息失败:'.$exception->getMessage(),$user->toArray());
        }
    }
    public function allotSendMessage(User $user,Coustomer $customer){
        $officialAccount = \EasyWeChat::officialAccount();
        return     $officialAccount->template_message->send([
            'touser' => $user->userWechat->openid,
            'template_id' => 'zEdOMrv8hPQTPLQja_EnqBjYc0m6PitdK6dk1R6w3Sg',
            'url' => '',
            "miniprogram"=>[
                "appid"=>"wxb07d0e98119debaa",
                "pagepath"=>"pages/index/index?type=3&id=".$customer->customer_id
           ],
            'data' => [
                'first' => '您分配到一个跟进任务',
                'keyword1'=>[$customer->name.'跟进中','#0066FF'],
                'keyword2' =>[$customer->project->name ?? '','#0066FF']  ,
                'keyword3'=>[Carbon::now(),'#0066FF'],
                'remark'=>'请登录小程序查看客户详情。'
            ],
        ]);
    }

}